﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_VendorController : MvcControllerBase
    {
        private VendorBLL vendorBLL = new VendorBLL();

        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]

        public ActionResult CommentIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]

        public ActionResult CommentForm()
        {
            return View();
        }
        #endregion

        #region 查询数据

        public ActionResult GetHtml(string SearchKeyWord, string BusinessScope = "", string ParentId = "")
        {
            var data = vendorBLL.GetList(SearchKeyWord, BusinessScope, ParentId).OrderBy(t => t.CreateDate);
            StringBuilder _Html = new StringBuilder();
            var index = 1;
            foreach (var item in data)
            {
                _Html.Append("<tr><td>" + index + "</td><td>" + item.EnCode + "</td><td>" + item.FullName + "</td>");
                _Html.Append("<td>" + item.ShortName + "</td><td>" + item.Nature + "</td><td>" + item.Manager + "</td><td>" + item.BusinessScope + "</td>");
                _Html.Append("<td><button type='button' class='btn btn-sm btn-warning' onclick='btn_add(\"" + item.Id + "\")'><i class='fa fa-pencil'></i> 编辑</button><button type='button' class='btn btn-sm btn-danger' onclick='btn_delete(\"" + item.Id + "\")'><i class='fa fa-trash-o'></i> 删除</button></td>");
                index++;
            }
            var model = data.OrderByDescending(t => t.ModifyDate).FirstOrDefault();
            var obj = new { Html = _Html.ToString(), ModifyDate = model == null ? null : model.ModifyDate != null ? model.ModifyDate : model.CreateDate, Count = data.Count() };
            return Content(obj.ToJson());
        }
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = vendorBLL.GetPageList(pagination, queryJson);
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = new OrganizeCache().GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data.Where(t => t.OrganizeId == null || organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    data = data.Where(t => t.OrganizeId != null && OrganizeId.Contains(t.OrganizeId)).ToList();
                }
            }
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 查询实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ActionResult GetFormJson(string keyValue)
        {
            var data = vendorBLL.GetEntity(keyValue);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取经营范围
        /// </summary>
        /// <returns></returns>
        public ActionResult GetFax()
        {
            DataItemDetailBLL dataitemdetailBLL = new DataItemDetailBLL();
            DataItemBLL dataitemBLL = new DataItemBLL();
            var itemId = dataitemBLL.GetEntity("", "经营范围").ItemId;
            var datacategory = dataitemdetailBLL.GetList(itemId);
            return Content(datacategory.ToJson());
        }
        /// <summary>
        /// 获取经营范围树形JSON
        /// </summary>
        /// <returns>返回树形Json</returns>
        [HttpGet]
        public ActionResult GetTreeFax()
        {
            DataItemDetailBLL dataitemdetailBLL = new DataItemDetailBLL();
            DataItemBLL dataitemBLL = new DataItemBLL();
            var itemId = dataitemBLL.GetEntity("", "经营范围").ItemId;
            var datacategory = dataitemdetailBLL.GetList(itemId);
            var treeList = new List<TreeEntity>();
            foreach (var item in datacategory)
            {
                #region 机构
                TreeEntity tree = new TreeEntity();
                tree.id = item.ItemId;
                tree.text = item.ItemName;
                tree.value = item.ItemValue;
                tree.parentId = "0";
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = false;
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 获取供应商树形JSON
        /// </summary>
        /// <returns>返回树形Json</returns>
        [HttpGet]
        public ActionResult GetTreeJson(string keyValue = "")
        {
            var datacategory = vendorBLL.GetList();
            if (!string.IsNullOrEmpty(keyValue))
                datacategory = datacategory.Where(t => t.Id != keyValue).ToList();
            var treeList = new List<TreeEntity>();
            foreach (var item in datacategory)
            {
                #region 机构
                TreeEntity tree = new TreeEntity();
                bool hasChildren = datacategory.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.FullName;
                if (item.ParentId == "0")
                {
                    tree.parentId = "0";
                }
                else
                {
                    tree.parentId = item.ParentId;
                }
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeToJson());
        }
        #endregion

        #region 检验数据

        /// <summary>
        /// 检验供应商编号是否存在
        /// </summary>
        /// <param name="EnCode"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistEnCode(string Code, string keyValue)
        {
            bool IsOk = vendorBLL.ExistEnCode(Code, keyValue);
            return Content(IsOk.ToString());
        }
        /// <summary>
        /// 名称不能重复
        /// </summary>
        /// <param name="FullName">名称</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistFullName(string FullName, string keyValue)
        {
            bool IsOk = vendorBLL.ExistFullName(FullName, keyValue);
            return Content(IsOk.ToString());
        }
        #endregion


        #region 提交数据

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult RemoveForm(string keyValue)
        {
            vendorBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        ///// <summary>
        ///// 删除评论
        ///// </summary>
        ///// <param name="keyValue">主键值</param>
        ///// <param name="departmentEntity">实体</param>
        ///// <returns></returns>
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //[AjaxOnly]
        //public ActionResult RemoveCommentForm(string keyValue)
        //{
        //    vendorBLL.RemoveCommentForm(keyValue);
        //    return Success("操作成功。");
        //}

        /// <summary>
        /// 保存表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="departmentEntity">实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, VendorEntity vendorEntity)
        {
            if (vendorEntity.ParentId == null)
            {
                vendorEntity.ParentId = "0";
            }
            vendorBLL.SaveForm(keyValue, vendorEntity);
            return Success("操作成功。");
        }

        #endregion
    }
}
